package com.huxun.service.Impl;

import com.huxun.bean.Cart;
import com.huxun.bean.Item;
import com.huxun.bean.Order;
import com.huxun.mapper.OrderMapper;
import com.huxun.service.CartService;
import com.huxun.service.DeskService;
import com.huxun.service.ItemService;
import com.huxun.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    CartService cartService;
    @Autowired
    DeskService deskService;
    @Autowired
    ItemService itemService;

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    @Override
    public int addOrder(int desk_id) {
        List<Cart> carts = cartService.getCarts(desk_id);
        double sum=0.0;
        for (Cart cart : carts) {
            sum=sum+cart.getTotal();
        }
        Order order = new Order();
        order.setDesk(deskService.getById(desk_id));
        order.setState(0);
        order.setTotalfee(sum);
        //新增订单表（返回订单主键）
        int count = orderMapper.addOrder(order);
        System.out.println("新增order表成功之后的主键是："+order.getOid());

        int index=0;
        for (Cart cart : carts) {
            Item item = new Item();
            item.setFood(cart.getFood());
            item.setOrder(order);
            item.setNum(cart.getNum());
            itemService.addItem(item);
            index++;
        }
        //清空购物车
        cartService.deleteCart(desk_id);
        return count+index;
    }

    @Override
    public Order getByDeskId(int desk_id) {
        return orderMapper.getByDeskId(desk_id);
    }
}
